package com.lvyp.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvyp.server.config.security.JwtTokenUtil;
import com.lvyp.server.mapper.AdminMapper;
import com.lvyp.server.mapper.AdminRoleMapper;
import com.lvyp.server.mapper.RoleMapper;
import com.lvyp.server.pojo.Admin;
import com.lvyp.server.pojo.AdminRole;
import com.lvyp.server.pojo.RespBean;
import com.lvyp.server.pojo.Role;
import com.lvyp.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lvyp
 * @since 2021-04-24
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Resource  //
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private AdminRoleMapper adminRoleMapper;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private RoleMapper roleMapper;



    /**
     * 登录之后返回token给前端
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        /*-----------------验证码校验-----------------*/
        String captcha = (String) request.getSession().getAttribute("captcha");  // 获取后端生成的验证码
        // 判断是否为空，判断后端生成的验证码 和 用户输入的验证码是否一样，忽略大小写比较
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码输入错误，请重新输入!");
        }

        /*------------------登录认证----------------*/
        // 根据用户名获取用户信息，再赋值给userDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);  // 用户信息：Admin(id=1, name=系统管理员, phone=13812361398, telephone=71937538,.....
        // 账号和密码验证
        if (null==userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("用户名或密码不正确");
        }
        // 判断账户是否禁用
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员！");
        }

        // 将登录后的用户信息放到 security上下文中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 根据用户信息生成token并返回给前端
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功",tokenMap);  // 返回数据给controller，再返回给前端

    }

    /**
     * 根据用户名查询用户，返回一个admin用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        // 根据用户名去数据库查询用户信息
        return adminMapper.selectOne(new QueryWrapper<  Admin>()
                .eq("username",username)
                .eq("enabled",true));
    }

    /**
     * 根据用户id查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }

    /**
     * 查询所有操作员：不需要查询当前登录用户，因为个人中心可以查看，没必要查询
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        // 获取当前登录用户信息
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return adminMapper.getAllAdmins(admin.getId(),keywords);
    }

    /**
     * 更新用户的角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        // 先删除
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        // 更新
        Integer result = adminRoleMapper.addAdminRole(adminId,rids);
        if (rids.length == result) {
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);  // 查询指定的用户
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){  // 判断传进来的老密码和数据库中的密码是否一致，如果一致才更新密码
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);  // 更新密码
            if (1==result) {
                return RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");
    }

    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int i = adminMapper.updateById(admin);
        if (i == 1){
            Admin principal = (Admin) authentication.getPrincipal();  // 获取当前用户信息
            principal.setUserFace(url);  // 更新用户信息
            //更新Authentication全局上下文
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }
}
